<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>LayIM 移动版 本地演示</title>
		<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
		<meta name="format-detection" content="telephone=no">
		<link rel="stylesheet" href="Public/layui/css/layui.mobile.css">
	</head>
	<body>
		<style>
			.layui-layim {
				bottom: 0px;
				top: 70px;
			}
			.hide_mobile_chat {
				display: none;
			}
			.layui-layim-tab {
				position: fixed;
				border: 0px;
				background: #2794eb;
				top: 0px;
				padding-top: 20px;
			}
			.layui-layim-tab i {
				display: none;
			}
			.layui-layim-tab li span {
				display: inline;
				box-sizing: border-box;
				font-size: 16px;
				line-height: 50px;
				padding-top: 7px;
				padding-bottom: 7px;
				padding-left: 15px;
				padding-right: 15px;
			}
			.layui-layim-tab li.layim-this span {
				color: #fff;
				border-bottom: 3px solid #fff;
			}
			.layui-layim-tab li {
				color: #fff;
				width: 50%;
			}
			.layui-layim-tab li:nth-child(3) {
				display: none;
			}
			#layui-m-layer0 .layim-content {
				margin-top: 0px;
			}
			#layui-m-layer0 .layim-title {
				display: none;
			}
			.layim-title {
				padding-top: 20px;
			}
			.layim-content {
				margin-top: 20px;
			}
			#layui-m-layer0 .layim-content {
				top: 0px;
			}
			.layim-tab-content {
				top: 70px;
			}
			.layim-tab-content:nth-child(1) {
				margin-top: 50px;
			}
			.layim-tab-content:nth-child(2) {
				position: fixed;
				width: 100%;
				display: none;
				z-index: 2;
				bottom: 0px;
				overflow-y: auto;
			}
			.layim-tab-content:nth-child(3) {
				position: fixed;
				width: 100%;
				display: block;
				top: 70px;
			}

		</style>
		<script src="Public/layui/layui.js"></script>

		<script>
			var msg_box_url = "/index.php?m=&c=Message&a=box";
			var chat_bind_url = '/index.php?m=&c=Chat&a=bind';
			var chat_init_url = '/index.php?m=&c=Chat&a=init';
			var chat_send_message_url = '/index.php?m=&c=Chat&a=send_message';
			var chat_member_url = '/index.php?m=&c=Chat&a=send_message';
			var chat_upload_img_url = '/index.php?m=&c=Chat&a=upload_img';
			var chat_upload_file_url = '/index.php?m=&c=Chat&a=upload_file';
			var chat_log_url = '/index.php?m=&c=Chat&a=chat_log';
			var push_server = "/index.php?m=&c=push&a=server";

			var is_app = false;

			var WEB_SOCKET_SWF_LOCATION = "./static/swf/WebSocketMain.swf";
			var WEB_SOCKET_DEBUG = true;
			var WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true;

			function load_js(src, callback) {
				var srcArray = src.split("?")[0].split("/");
				var scr_src = srcArray[srcArray.length - 1];

				// 判断要 添加的脚本是否存在如果存在则不继续添加了
				var scripts = document.getElementsByTagName("script");
				if (!!scripts && 0 != scripts.length) {
					for (var i = 0; i < scripts.length; i++) {
						if (-1 != scripts[i].src.indexOf(scr_src)) {
							callback();
							return true;
						}
					}
				}

				// 不存在需要的则添加
				var head = document.getElementsByTagName("head")[0];
				var script = document.createElement("script");
				script.setAttribute("type", "text/javascript");
				script.setAttribute("src", src);
				script.setAttribute("async", true);
				script.setAttribute("defer", true);
				head.appendChild(script);

				//fuck ie! duck type
				if (document.all) {
					script.onreadystatechange = function() {
						var state = this.readyState;
						if (state === 'loaded' || state === 'complete') {
							callback();
						}
					};
				} else {
					//firefox, chrome
					script.onload = function() {
						callback();
					};
				}
			}

			//获取最新推送
			function get_push() {
				var d = new Date().getTime();
				$.ajax({
					type : "POST",
					url : push_server + '&' + d,
					dataType : "json",
					success : function(ret) {
						if (ret.status) {
							$msg = $.parseJSON(ret.data.data);
							push_info($msg);
							get_push();
						}
					}
				});
			};

			//显示推送信息
			function push_info($msg) {
				var position;
				var title;
				var content;
				if ($msg.action.length) {
					title = '[' + $msg.type + '] [' + $msg.action + ']';
				} else {
					title = '[' + $msg.type + ']';
				}
				content = $msg.title;
				if (!is_app) {
					api.notification({
						notify : {
							title : title,
							content : content
						}
					}, function(ret, err) {
						var id = ret.id;
					});
				} else {
					alert(title + content);
				}
			}

			var laychat = {
				appName : '消息',
				initUrl : './init.php', // 初始化好友列表和群组接口，这个接口返回个json，格式见
				sendMessageUrl : './send_message.php', // 发消息接口
				membersUrl : './members.php',
				uploadImageUrl : './upload_img.php',
				uploadFileUrl : './upload_file.php',
				chatLogUrl : './chat_log.php',
				bindUrl : './bind.php',
				updateSignUrl : './update_sign.php',
				msgBoxUrl : './msg_box.php',
				agreeUrl : './agree.php',
				getNoticeUrl : './get_notice.php',
				isMobile : false,
				address : 'ws://' + document.domain + ':8282',
				setMin : false,
				findUrl : false,
				inited : 0,
				socket : null,
				jq : null,
				open : function() {
					if (this.inited)
						return;
					if (!this.jq)
						this.jq = $;
					this.connectWorkerman();
					this.inited = 1;
				},
				connectWorkerman : function() {
					laychat.socket = new WebSocket(laychat.address);
					laychat.socket.onopen = function() {
						laychat.socket.send(JSON.stringify({
							type : 'init'
						}));
					};

					laychat.socket.onmessage = function(e) {
						var msg = JSON.parse(e.data);
						// 如果layim还没有初始化就收到消息则忽略（init消息除外）
						if (!msg.message_type || (msg.message_type != 'init' && !layui.layim))
							return;

						switch(msg.message_type) {
						// 初始化im

						case 'init':
							// ajax请求，绑定client_id和uid
							laychat.jq.post(laychat.bindUrl, {
								client_id : msg.client_id
							}, function(data) {
								if (data.code == 0) {
									// im获得初始化数据，当前用户，好友列表等数据
									laychat.jq.post(laychat.initUrl, {}, function(initData) {
										if (initData.code != 0) {
											alert('laychat服务端返回失败：' + initData.msg);
										} else {
											laychat.initIM(data, initData.data);
										}
									}, 'json');
								} else {
									alert('laychat服务端返回失败：' + data.msg);
								}
							}, 'json');
							return;
						// 添加一个用户到好友列表
						case 'addList':
							if (laychat.jq('#layim-friend' + msg.data.id).length == 0 && layui.layim.cache() && layui.layim.cache().id != msg.data.id) {
								return layui.layim.addList && layui.layim.addList(msg.data);
							}
							if (msg.data.type == 'friend') {
								layui.layim.setFriendStatus && layui.layim.setFriendStatus(msg.data.id, 'online');
							}
							return;
						// 收到一个消息
						case 'chatMessage':

							if (msg.data.type == 'push') {
								get_push();
								return false;
							}
							if (msg.data.type == 'group') {
								if (msg.data.from_id != layui.layim.cache().mine.id) {
									layui.layim.getMessage(msg.data);
								}
							} else if (layui.layim.cache().mine.id != msg.data.id) {
								layui.layim.getMessage(msg.data);
							}
							laychat.unReadMessageCount(layui.layim);
							return;
						case 'msgbox':
							layui.layim.msgbox && layui.layim.msgbox(msg.count);
							return;
						// 退出
						case 'logout':
						// 隐身
						case 'hide':
							return layui.layim.setFriendStatus && layui.layim.setFriendStatus(msg.id, 'offline');
						// 上线
						case 'online':
							return layui.layim.setFriendStatus && layui.layim.setFriendStatus(msg.id, 'online');
						}
					};
					laychat.socket.onclose = laychat.connectWorkerman;
				},
				sendHeartbeat : function() {
					if (this.socket && this.socket.readyState == 1) {
						this.socket.send(JSON.stringify({
							type : 'ping'
						}));
					}
				},
				unReadMessageCount : function(layim) {
					var cache = layim.cache();
					count = 0;
					for (k in cache.message) {
						count += cache.message[k].length;
					}
					if (count == 0) {
						count = '';
					}
					$('#chat_count').text(count);
				},
				initIM : function(msg_data, init_data) {
					var unread_msg_tips = function(msg_data) {
						// 离线消息
						for (var key in msg_data.unread_message) {
							layui.layim.getMessage(JSON.parse(msg_data.unread_message[key]));
						}
						if (msg_data.unread_notice_count) {
							// 设置消息盒子未读计数
							layui.layim.msgbox && layui.layim.msgbox(msg_data.unread_notice_count);
						}
						return;
					};

					// layim已经初始化了，则只提示未读消息
					if (this.inited == 2) {
						return unread_msg_tips(msg_data);
					}
					this.inited = 2;

					// 心跳数据，用来保持长链接，避免socket链接长时间不通讯被路由节点防火墙关闭
					setInterval('laychat.sendHeartbeat()', 12000);

					layui.use('mobile', function(layim) {

						var mobile = layui.mobile, layim = mobile.layim, layer = mobile.layer;
						layui.layim = layim;
						layui.layer = layer;

						laychat.unReadMessageCount(layui.layim);
						layui.layim.config({
							//初始化接口
							chatTitleColor : "#2794eb",
							isNewFriend : false,
							init : init_data,

							//查看群员接口
							members : {
								url : laychat.membersUrl
							},

							// 上传图片
							uploadImage : {
								url : laychat.uploadImageUrl
							},

							// 上传文件
							uploadFile : {
								url : laychat.uploadFileUrl
							},
							msgbox : laychat.msgBoxUrl,

							//聊天记录地址
							chatLog : laychat.chatLogUrl,
							find : laychat.findUrl,

							//是否授权
							copyright : true,
							title : laychat.appName,
							min : laychat.setMin,
							moreList : [{
								alias : 'msgbox',
								title : '消息盒子',
								iconUnicode : '&#xe645;', //图标字体的unicode，可不填
								iconClass : '' //图标字体的class类名
							}]
						});
						layim.on('chatChange', function(data) {
							api.setFrameAttr({
								name : 'chat',								
								rect : {
									x : 0, //左上角x坐标
									y : 0, //左上角y坐标
									w : 'auto', //宽度，若传'auto'，页面从x位置开始自动充满父页面宽度
									h : 'auto',
								}
							});
						});
						layim.on('back', function() {
							var footer_h = api.getPrefs({
								sync : true,
								key : 'footer_h'
							});
							api.setFrameAttr({
								name : 'chat',								
								rect : {
									x : 0, //左上角x坐标
									y : 0, //左上角y坐标
									w : 'auto', //宽度，若传'auto'，页面从x位置开始自动充满父页面宽度
									h : api.winHeight - footer_h
								}
							});
						});
						//监听点击更多列表
						layim.on('moreList', function(obj) {
							switch(obj.alias) {
							case 'msgbox':
								api.setFrameAttr({
									name : 'chat',
									rect : {
										x : 0, //左上角x坐标
										y : 0, //左上角y坐标
										w : 'auto', //宽度，若传'auto'，页面从x位置开始自动充满父页面宽度
										h : 'auto',
									}
								});
								layim.panel({
									title : '消息盒子'//分享
									,
									tpl : '<iframe style="border:0px;scrolling:no;padding: 0px;width:100%;height:100%;" src="{{d.data.test}}">'//模版
									,
									data : {
										test : laychat.msgBoxUrl
									}
								});
								//模拟标记“发现新动态”为已读
								layim.showNew('More', false);
								layim.showNew('find', false);
								break;
							}
						});
						//监听发送消息
						layim.on('sendMessage', function(data) {
							laychat.jq.post(laychat.sendMessageUrl, {
								data : data
							}, function(data) {
								if (data.code != 0) {
									layui.layer.msg(data.msg, {
										time : 7000
									});
								}
							}, 'json');
						});

						//监听在线状态的切换事件
						layim.on('online', function(data) {
							laychat.socket.send(JSON.stringify({
								type : data
							}));
						});

						//更改个性签名
						layim.on('sign', function(value) {
							laychat.jq.post(laychat.updateSignUrl, {
								sign : value
							}, function(data) {
								if (data.code != 0) {
									layui.layer.msg(data.msg, {
										time : 7000
									});
								}
							}, 'json');
						});

						//layim建立就绪
						layim.on('ready', function(res) {
							// 离线消息
							laychat.unReadMessageCount(layui.layim);
							return unread_msg_tips(msg_data);
						});
					});
				}
			};

			apiready = function() {
				layui.config({
					base : 'Public/layui/js/',
				}).use('jquery', function() {
					$ = layui.jquery;
					web_socket_url = 'Public/layui/js/web_socket.js';
					load_js(web_socket_url, function() {
						// 置服务端websocket地址
						laychat.address = 'ws://' + document.domain + ':8282';

						//最小化
						laychat.setMin = true;
						laychat.msgBoxUrl = msg_box_url;

						// 置服务端websocket地址
						laychat.bindUrl = chat_bind_url;
						laychat.initUrl = chat_init_url;
						laychat.sendMessageUrl = chat_send_message_url;
						laychat.membersUrl = chat_member_url;
						laychat.chatLogUrl = chat_log_url;
						laychat.uploadImageUrl = chat_upload_img_url;
						laychat.uploadFileUrl = chat_upload_file_url;

						// 打开laychat对话框
						laychat.open();
					});
				});
			};
			apiready();
		</script>
	</body>
</html>
